#include <my_header.h>
/*03_epoll_et 测试用服务端 */
/* Usage: */
int main(int argc, char *argv[])
{
    //  ./03_epoll_et.c 192.168.217.128 12345
    ARGS_CHECK(argc, 3);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    int flag = 1; //  启用SO_REUSEADDR
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    struct sockaddr_in addr;

    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));

    ERROR_CHECK(ret, -1, "bind");
    listen(sockfd, 10);

    int netfd = accept(sockfd, NULL, NULL);

    char buf[4096];
    int epfd = epoll_create(1); //  epfd 可以访问epoll文件对象
    struct epoll_event event;
    event.events = EPOLLIN;       //  可读时就绪
    event.data.fd = STDIN_FILENO; //  将来就绪之后填入自己的文件描述符
    epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    event.events = EPOLLIN | EPOLLET; //  可读时就绪，边缘触发
    event.data.fd = netfd;
    epoll_ctl(epfd, EPOLL_CTL_ADD, netfd, &event);
    struct epoll_event readyset[1024];
    while (1)
    {
        int readynum = epoll_wait(epfd, readyset, 1024, -1);
        printf("epoll_wait ready!\n");
        for (int i = 0; i < readynum; ++i)
        {
            if (readyset[i].data.fd == STDIN_FILENO)
            {
                bzero(buf, sizeof(buf));
                read(STDIN_FILENO, buf, sizeof(buf));
                send(netfd, buf, strlen(buf), 0);
            }
            else if (readyset[i].data.fd == netfd)
            {
                while (1)
                {
                    bzero(buf, sizeof(buf));
                    ssize_t sret = recv(netfd, buf, 2, MSG_DONTWAIT);
                    if (sret == -1)
                    { //  没数据
                        break;
                    }
                    if (sret == 0)
                    {
                        goto end;
                    }
                    printf("buf = %s\n", buf);
                }
            }
        }
    }
end:
    return 0;
}
